
import store from '../lib/store';
import { onHide } from '@dcloudio/uni-app';
import { ref, onBeforeUnmount } from 'vue';


/** 课程还有5分钟倒计时 */
const useCountdown = () => {
	/** 计时器 */
	const timer = ref(null);
	
	/** 词汇相关共享数据 */
	const storeData = store();
	
	/** 清除计时器 */
	const clear = () => {
		clearInterval(timer.value);
		timer.value = null;
	};
	
	/** 开始计时 */
	const start = (callback: () => void) => {
		if (!storeData.countdownTime || storeData.query.learnType === 1) return;
		let newdate = 0;
		const setIntervalCallback = () => {
			const date = new Date();
			const endDate = Date.parse(storeData.countdownTime);
			const startDate = Date.parse(date as unknown as string);
			newdate = endDate - startDate;
			newdate < 0 && clear();
			if (newdate === 0) {
				clear();
				uni.showModal({ 
					title: '温馨提示', 
					showCancel: false, 
					confirmText: '学后检测' ,
					success: ({ confirm }) => confirm && callback?.(),
					content: '当前课程已结束，请进入学后检测提交课程学习成果！'
				});
			};
			console.log('newdate', newdate);
			if (newdate === 300000) {
				uni.showModal({ 
					title: '温馨提示', 
					showCancel: false, 
					confirmText: '关闭',
					content: '课程还有5分钟结束，请尽快提交学后检测！'
				});
			};
		};
		
		setIntervalCallback();
		if (newdate > 0) timer.value = setInterval(setIntervalCallback, 1000);
	};
	
	
	onHide(clear);
	onBeforeUnmount(clear);
	return { start, clear };
};


export default useCountdown;